package com.dfdchem.imd.kaiwu.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.MainActivity;
import com.dfdchem.imd.kaiwu.adapter.AlarmListAdapter;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.interfaces.RecyclerItemClickListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.model.AlarmCountModel;
import com.dfdchem.imd.kaiwu.model.AlarmModel;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.RespList;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.UrlParse;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;
import java.util.Map;


public class AlarmFragment extends Fragment implements OnHttpResponseListener, View.OnClickListener, OnRefreshListener {
    private static final String TAG = "AlarmFragment";

    private MainActivity mainActivity;

    private View alarm_list;
    private TextView alarm_list_count;

    private View alarm_config;
    private TextView alarm_config_count;

    private View alarm_point_list;

    private View alarm_subscribe;
    private TextView alarm_subscribe_count;

    private TextView no_data_tips;

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private AlarmListAdapter alarmListAdapter;

    private static final int request_code_get_count = 1;
    private static final int request_code_get_list = 2;

    private boolean isRefresh = false;

    private int request_page = 1;
    private int request_limit = 10;

    private String url_alarm_handleList = "http://172.21.10.61:88/#/alarm/handleList";
    private String url_alarm_configList = "http://172.21.10.61:88/#/alarm/configList";
    private String url_alarm_dcsList = "http://172.21.10.61:88/#/alarm/dcsList";
    private String url_alarm_subscribeList = "http://172.21.10.61:88/#/alarm/subscribeList";
    private String url_alarm_detail = "http://172.21.10.61:88/#/alarm/handleInfo?No=";

    public static AlarmFragment newInstance() {
        return new AlarmFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();
        refreshData();
    }

    @Override
    public View onCreateView(final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_alarm,
                container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        alarm_list = view.findViewById(R.id.alarm_list);
        alarm_list_count = view.findViewById(R.id.alarm_list_count);
        alarm_list_count.setVisibility(View.INVISIBLE);

        alarm_config = view.findViewById(R.id.alarm_config);
        alarm_config_count = view.findViewById(R.id.alarm_config_count);
        alarm_config_count.setVisibility(View.INVISIBLE);

        alarm_point_list = view.findViewById(R.id.alarm_point_list);

        alarm_subscribe = view.findViewById(R.id.alarm_subscribe);
        alarm_subscribe_count = view.findViewById(R.id.alarm_subscribe_count);
        alarm_subscribe_count.setVisibility(View.INVISIBLE);

        no_data_tips = view.findViewById(R.id.no_data_tips);

        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);

        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);

        alarmListAdapter = new AlarmListAdapter(null);
        recyclerView.setAdapter(alarmListAdapter);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 初始化MainActivity
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        }

        initListeners();
    }

    private void initListeners() {
        alarm_list.setOnClickListener(this);
        alarm_config.setOnClickListener(this);
        alarm_point_list.setOnClickListener(this);
        alarm_subscribe.setOnClickListener(this);

        alarmListAdapter.setContext(getActivity());

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(getActivity(), recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        AlarmModel alarmModel = alarmListAdapter.getAlarmModels().get(position);
                        Uri uri = Uri.parse(url_alarm_detail + alarmModel.getNo());

                        mainActivity.handleScheme(uri);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        Log.d(TAG, "addOnItemTouchListener onLongItemClick");
                    }
                })
        );
    }

    private void refreshData(){
        // mainActivity.showProgressDialog("加载中...");
        isRefresh = true;

        User user = DataManager.getInstance().getUser();
        if (user == null || user.getId() <= 0) return;

        // TODO 测试阶段
        if (DataManager.getInstance().isTest()) {
            String url = "arouter://kaiwu/dialog?type=2&title=提示：&content=你当前处于测试模式下，看到的是测试用户的数据，并非正式数据。&confirmText=确定";
            Map<String, String> params = UrlParse.getUriParams(Uri.parse(url));
            assert getFragmentManager() != null;
            new CommonDialog(mainActivity, params).show(getFragmentManager(), "CommonDialog");

            user.setId(100000);
        }

        mainActivity.runThread(TAG + "getCount", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getAlarmCount(user.getId(), request_code_get_count, AlarmFragment.this);
            }
        });

        mainActivity.runThread(TAG + "getList", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getAlarmList(request_code_get_list, AlarmFragment.this);
            }
        });
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        mainActivity.dismissProgressDialog();

        if (e != null) {
            isRefresh = false;
            if (refreshLayout != null) {
                refreshLayout.finishRefresh();
            }
            Toast.makeText(mainActivity, "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode) {
            case request_code_get_count:
                isRefresh = false;
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }
                Resp<AlarmCountModel> resp = JSON.parseResp(resultJson, AlarmCountModel.class);
                if (resp == null || (resp.getCode() != 200)) {
                    Toast.makeText(getActivity(), resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                AlarmCountModel alarmCountModel = resp.getData();

                if (alarmCountModel == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }

                alarm_list_count.setText(alarmCountModel.getTotalAlarm() + "");
                alarm_list_count.setVisibility(alarmCountModel.getTotalAlarm() > 0 ? View.VISIBLE : View.GONE);

                alarm_subscribe_count.setText(alarmCountModel.getTotalSubscription() + "");
                alarm_subscribe_count.setVisibility(alarmCountModel.getTotalSubscription() > 0 ? View.VISIBLE : View.GONE);

                mainActivity.setNCBadger(1, alarmCountModel.getTotalAlarm(), true);

                break;
            case request_code_get_list:
                isRefresh = false;
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }

                RespList<AlarmModel> respList = JSON.parseRespList(resultJson, AlarmModel.class);
                if (respList == null || (respList.getCode() != 200)) {
                    Toast.makeText(getActivity(), respList != null ? respList.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<AlarmModel> alarmModelList = respList.getData();

                request_page = respList.getPage();
                request_limit = respList.getLimit();

                if (alarmModelList == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }

                if (refreshLayout.getState() == RefreshState.None || refreshLayout.getState() == RefreshState.Refreshing) {
                    alarmListAdapter.setAlarmModels(alarmModelList);
                    alarmListAdapter.notifyDataSetChanged();
                    refreshLayout.finishRefresh(250);

                    no_data_tips.setVisibility(alarmModelList.size() == 0 ? View.VISIBLE : View.GONE);

                } else if (refreshLayout.getState() == RefreshState.Loading) {
                    if (alarmModelList.size() > 0) {
                        List<AlarmModel> tmpList = alarmListAdapter.getAlarmModels();
                        if (tmpList != null) {
                            tmpList.addAll(alarmModelList);
                        } else {
                            tmpList = alarmModelList;
                        }
                        alarmListAdapter.setAlarmModels(tmpList);

                        alarmListAdapter.notifyDataSetChanged();
                    }
                    if (alarmModelList.size() == 0 && request_page * request_limit >= respList.getRecordsTotal()) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishLoadMore(250);
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        Uri uri = null;
        switch (v.getId()) {
            case R.id.alarm_list:
                uri = Uri.parse(url_alarm_handleList);
                mainActivity.handleScheme(uri);
                break;
            case R.id.alarm_config:
                uri = Uri.parse(url_alarm_configList);
                mainActivity.handleScheme(uri);
                break;
            case R.id.alarm_point_list:
                uri = Uri.parse(url_alarm_dcsList);
                mainActivity.handleScheme(uri);
                break;
            case R.id.alarm_subscribe:
                uri = Uri.parse(url_alarm_subscribeList);
                mainActivity.handleScheme(uri);
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }
}
